import os
import csv
import json
from math import ceil
from geopy import distance

class SpatialRegion:
    def __init__(self, minlat, minlon, maxlat, maxlon, xstep, ystep, vocab_start):
        assert minlat < maxlat, "minlat should be smaller than maxlat"
        assert minlon < maxlon, "minlon should be smaller than maxlon"
        self.minlat = minlat
        self.minlon = minlon
        self.maxlat = maxlat
        self.maxlon = maxlon

        self.xstep = xstep
        self.ystep = ystep

        self.vocab_start = vocab_start

        self.num_x = ceil(distance.distance(
            (self.minlat, self.minlon), (self.minlat, self.maxlon)).km * 1000 / self.xstep)
        self.num_y = ceil(distance.distance(
            (self.minlat, self.minlon), (self.maxlat, self.minlon)).km * 1000 / self.ystep)

    def in_region(self, lat, lon):
        return self.minlat <= lat <= self.maxlat and self.minlon <= lon <= self.maxlon

    def offset(self, lat, lon):
        x_offset = distance.distance(
            (self.minlat, self.minlon), (self.minlat, lon)).km * 1000
        y_offset = distance.distance(
            (self.minlat, self.minlon), (lat, self.minlon)).km * 1000
        return x_offset, y_offset

    def coord2cell(self, lat, lon):
        assert self.in_region(lat, lon), f"({lat}, {lon}) not in area"
        x_offset, y_offset = self.offset(lat, lon)
        x_offset = ceil(x_offset / self.xstep)
        y_offset = ceil(y_offset / self.ystep)
        if x_offset == 0:
            x_offset = 1
        if  y_offset == 0:
            y_offset = 1
        return self.num_x * (y_offset - 1) + x_offset - 1 + self.vocab_start

if __name__ == '__main__':
    # SR = SpatialRegion(41.4459657, 11.7531545505395, 42.302192553508, 12.9634722613942,100,100,1)
    # for i in range(400):
    #     filename = './trajectory/' + "ID_" +str(i) + '.csv'
    #     filename2 = './grid/' + "ID-" + str(i) + '.csv'
    #     if not os.path.exists(filename):
    #         pass
    #     else:
    #         with open(filename, "r") as f:
    #             reader = csv.reader(f)
    #             regions = []
    #             for trajectories in reader:
    #                 region = []
    #                 for trajectory in trajectories:
    #                     trajectory = trajectory.strip(')').strip('(').split(',')
    #                     lat = float(trajectory[0])
    #                     lon = float(trajectory[1])
    #                     region.append(SR.coord2cell(lat, lon))
    #                 regions.append(region)
            
    #         with open(filename2, 'w', newline='') as csvfile:
    #             spamwriter = csv.writer(csvfile)
    #             for item in regions:
    #                 spamwriter.writerow(item)


    # SR = SpatialRegion(41.4459657, 11.7531545505395, 42.302192553508, 12.9634722613942,100,100,1)
    # grid_statistic = {}
    # for i in range(400):
    #     filename = './trajectory/' + "ID_" +str(i) + '.csv'
    #     if not os.path.exists(filename):
    #         pass
    #     else:
    #         print(i)
    #         with open(filename, "r") as f:
    #             reader = csv.reader(f)
    #             for trajectories in reader:
    #                 for trajectory in trajectories:
    #                     trajectory = trajectory.strip(')').strip('(').split(',')
    #                     lat = float(trajectory[0])
    #                     lon = float(trajectory[1])
    #                     blk = SR.coord2cell(lat, lon)

    #                     if not grid_statistic.__contains__(blk):
    #                         grid_statistic[blk] = []
    #                     grid_statistic[blk].append((lat, lon))
            
    # json_data = json.dumps(grid_statistic, indent = 4)
    
    # with open('./grid/statistics.json', 'w') as f2:
    #     f2.write(json_data)
    SR = SpatialRegion(41.4459657, 11.7531545505395, 42.302192553508, 12.9634722613942,100,100,1)
    print(SR.coord2cell(41.89860,12.47684))